package com.example.scrambledpuzzle;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class PreloadedImageGallery extends Activity {
	
	int displayResourceId;
	ImageView Display;
	LinearLayout myGallery;
	Bitmap bm;
	Integer[] resourceImages={
			R.drawable.cow,
			R.drawable.dog ,
			R.drawable.elephant,
			R.drawable.fish,
			R.drawable.fox,
			R.drawable.peacock,
			//R.drawable.beavers,
		//	R.drawable.bike,
			//R.drawable.car
			
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_preloaded_image_gallery);
		Display=(ImageView) findViewById(R.id.IVDisplay);
		Display.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent= new Intent(PreloadedImageGallery.this,SwapPuzzle.class);
				
				intent.putExtra("BitmapImage", displayResourceId);
				startActivity(intent);
				finish();
				
			}
		});
		myGallery = (LinearLayout)findViewById(R.id.mygallery);
		for(int i=0; i< resourceImages.length;i++ ){
			myGallery.addView(insertPhoto(resourceImages[i]));
		}
	}
	
	View insertPhoto(final int resourceId){
		 bm= BitmapFactory.decodeResource(getResources(), resourceId);
		LinearLayout layout = new LinearLayout(getApplicationContext());
	     layout.setLayoutParams(new LayoutParams(pixelsFromDp(150), pixelsFromDp(150)));
	     layout.setGravity(Gravity.CENTER);
	     
	     ImageView imageView = new ImageView(getApplicationContext());
	     imageView.setLayoutParams(new LayoutParams(pixelsFromDp(120), pixelsFromDp(120)));
	     imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
	     imageView.setImageBitmap(bm);
	     //bm.recycle();
	     imageView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Display.setImageResource(resourceId);
				displayResourceId=resourceId;
			}
		});
	     layout.addView(imageView);
	     return layout;
	}

	private int pixelsFromDp(int pixels) {
		
		return (int) (pixels * getResources().getDisplayMetrics().density + 0.5f);
	}

	protected void onDestroy(){
		bm.recycle();
		bm=null;
		//myGallery = (LinearLayout)findViewById(R.id.mygallery);
		myGallery.removeAllViews();
		myGallery=null;
		super.onDestroy();
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.preloaded_image_gallery, menu);
		return true;
	}

}
